package com.xiaoxin.experience.service.net;

import com.xiaoxin.experience.service.net.model.StorageUnitEnum;
import com.xiaoxin.experience.util.StringUtil;
import com.xiaoxin.experience.util.ThreadUtil;
import org.springframework.scheduling.support.CronTrigger;

/**
 * <p>Simple life, simple work, don't complicate</p>
 *
 * @author 小心
 * @version 1.0.0
 * @date 2023/1/27
 */
public class NetMonitor
{
    private static long speed = 0L;

    static
    {
        init();
    }

    private static void init()
    {
        ThreadUtil.schedule(()->{speed = 0L;},new CronTrigger("0/1 * * * * ?"));
    }

    public static void stats(long size)
    {
        speed += size;
    }

    public static String getCurrentNetSpeed()
    {
        long currentSpeed = speed;
        double mb = StorageUnitEnum.BYTE.toMB(currentSpeed);
        if (mb > 1.0)
        {
            return StringUtil.floatFormat(mb) + "M/s";
        }
        double kb = StorageUnitEnum.BYTE.toKB(currentSpeed);
        if (kb > 1.0)
        {
            return StringUtil.floatFormat(kb) + "K/s";
        }
        return currentSpeed + "B/s";
    }
}
